package cn.dslcode.security.config.handler;

import cn.dslcode.common.web.WebUtil;
import cn.dslcode.common.web.response.CommonResponseCode;
import cn.dslcode.common.web.response.RestResponse;
import cn.dslcode.security.common.DataCenter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author dongsilin
 * @version 2018/4/8.
 *          权限不通过的处理
 */
@Slf4j
@Component
public final class CustomAccessExceptionHandler implements AuthenticationEntryPoint, AccessDeniedHandler {

    /**
     * 认证处理
     *
     * @param request
     * @param response
     * @param e
     * @throws IOException
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
        log.info("{}", e.getClass().getName());
        if (WebUtil.isAjax(request)) {
            WebUtil.output(response, RestResponse.build(CommonResponseCode.UNAUTHENTICATION), WebUtil.ResponseOutputType.JSON);
            return;
        }
        response.sendRedirect(DataCenter.loginFormUri);
    }

    /**
     * 没有权限处理
     *
     * @param request
     * @param response
     * @param e
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        log.info("{}", e.getClass().getName());
        if (WebUtil.isAjax(request)) {
            WebUtil.output(response, RestResponse.build(CommonResponseCode.UNAUTHORIZATION), WebUtil.ResponseOutputType.JSON);
            return;
        }
        response.sendRedirect(DataCenter.accessDenyUri);
    }

}